<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <!-- <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                title="新增网格"
                type="primary"
                icon="el-icon-plus"
                size="mini"
                circle
                @click="gridhandleAdd"
              ></el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                title="编辑网格"
                type="warning"
                icon="el-icon-edit"
                size="mini"
                circle
                @click="gridhandleEdit"
              ></el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                title="删除网格"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
                @click="gridhandleDelete"
              ></el-button>
            </el-col>
          </el-row>
          <ul class="grid">
            <li
              v-for="(item, index) in guserArr"
              :key="index"
              :class="[gridActiveindex === index ? 'grid-active' : '']"
              @click="gridItemClick(index)"
            >
              {{ item.gridAreaName }}
            </li>
          </ul>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <!-- <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入姓名"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="账号状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form> -->

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
        </el-row>

        <el-table
          v-loading="loading"
          :data="gridList"
          style="margin-top: 22px"
          stripe
          :header-cell-style="{
            background: '#e1f0ff',
            color: '#000000',
            'margin-top': '22px',
            height: '48px',
          }"
          :cell-style="{
            height: '46px',
            'boder-bottom': '0px',
            padding: '9px 0px',
          }"
        >
          <el-table-column label="网格员ID" align="center" prop="gridUserId" />
          <el-table-column
            label="归属网络片区ID"
            align="center"
            prop="gridAreaId"
          />
          <el-table-column label="姓名" align="center" prop="gridUserName" />
          <el-table-column
            label="手机号码"
            align="center"
            prop="gridUserPhone"
            width="120"
          />
          <el-table-column
            label="账号"
            align="center"
            prop="gridUserAccount"
          ></el-table-column>
          <el-table-column label="性别" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.gridUserSex == 'male'">男</span>
              <span v-else-if="scope.row.gridUserSex == 'female'">女</span>
            </template>
          </el-table-column>
          <el-table-column label="是否是网格长" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.gridUserLeaderFlag === 1">是</span>
              <span v-else-if="scope.row.gridUserLeaderFlag === 0">否</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.gridUserStatus === 1">停用</span>
              <span v-else-if="scope.row.gridUserStatus === 0">正常</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="300"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        /> -->
      </el-col>
    </el-row>

    <!-- 添加或编辑网格 -->
    <el-dialog
      :title="title"
      :visible.sync="gridOpen"
      width="400px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form
        ref="gridform"
        :model="gridform"
        :rules="gridRules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="网格名称" prop="gridAreaName">
              <el-input
                v-model="gridform.gridAreaName"
                placeholder="请输入网格名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="主要污染源" prop="mainWasteSource">
              <el-select
                v-model="gridform.mainWasteSource"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in pollutionSources"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="责任部门" prop="duteDept">
              <el-input
                v-model="gridform.duteDept"
                placeholder="请输入责任部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="责任领导" prop="duteLeader">
              <el-input
                v-model="gridform.duteLeader"
                placeholder="请输入责任领导"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="联系方式" prop="phone">
              <el-input
                v-model="gridform.phone"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGridForm">确 定</el-button>
        <el-button @click="gridCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属网格片区" prop="gridAreaName">
              <el-input
                v-model="gridAreaName"
                placeholder="请输入姓名"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="gridUserName">
              <el-input v-model="form.gridUserName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="gridUserPhone">
              <el-input
                v-model="form.gridUserPhone"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="gridUserEmail">
              <el-input
                v-model="form.gridUserEmail"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号" prop="gridUserAccount">
              <el-input
                v-model="form.gridUserAccount"
                placeholder="请输入账号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.gridUserId == undefined">
            <el-form-item label="密码" prop="gridUserPassword">
              <el-input
                v-model="form.gridUserPassword"
                placeholder="请输入密码"
                type="password"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="form.gridUserSex" placeholder="请选择">
                <el-option
                  v-for="dict in sexList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.gridUserStatus">
                <el-radio
                  v-for="(dict, dictInx) in statusOptions"
                  :key="dictInx"
                  :label="Number(dict.dictValue)"
                  >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否是网格长">
              <el-select v-model="form.gridUserLeaderFlag" placeholder="请选择">
                <el-option
                  v-for="item in isGridList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  guserAreaList,
  addGuserArea,
  editGuserArea,
  delGridArea,
  delGrid,
  addGuser,
  editGuser,
} from "@/api/system/grid";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  components: {},
  data() {
    var validatePass = (rule, value, callback) => {
      let num = 0;
      let reg1 = /\d/;
      if (reg1.test(value)) {
        num += 1;
      }
      let reg2 = /[A-Z]/;
      if (reg2.test(value)) {
        num += 1;
      }
      let reg3 = /[a-z]/;
      if (reg3.test(value)) {
        num += 1;
      }
      let reg4 = RegExp(
        /[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\‘)(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/
      );
      if (reg4.test(value)) {
        num += 1;
      }
      if (num >= 3) {
        callback();
      } else {
        callback(
          new Error(
            "密码要包含数字、小写字母、大写字母、特殊字符（任意三种一个组合）"
          )
        );
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: 1,
      },
      // 表单校验
      rules: {
        gridUserName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        gridUserAccount: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
        gridUserPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 8,
            max: 20,
            message: "长度在 8 到 20 个字符",
            trigger: "blur",
          },
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        gridUserEmail: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        gridUserPhone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      guserArr: [],
      gridActiveindex: 0,
      gridform: {},
      gridOpen: false,
      pollutionSources: [],
      gridRules: {
        gridAreaName: [
          { required: true, message: "网格名称不能为空", trigger: "blur" },
        ],
        duteDept: [
          { required: true, message: "责任部门不能为空", trigger: "blur" },
        ],
        duteLeader: [
          { required: true, message: "责任领导不能为空", trigger: "blur" },
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 是否显示弹出层
      open: false,
      isGridList: [
        { value: 0, label: "否" },
        { value: 1, label: "是" },
      ],
      sexList: [
        { value: "male", label: "男" },
        { value: "female", label: "女" },
      ],
      gridAreaName: "",
      gridList: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    // 网格list
    this.getGuserAreaList();
    // 获取主要污染源
    this.getDicts("WASTE_SOURCE_TAGS").then((response) => {
      this.pollutionSources = response.data;
    });
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    // this.getConfigKey("sys.user.initPassword").then((response) => {
    //   this.initPassword = response.data;
    // });
  },
  methods: {
    gridItemClick(index) {
      this.gridActiveindex = index;
      if (this.guserArr.length > 0) {
        this.gridList = this.guserArr[index].gridUserList;
      }
      this.loading = false;
    },
    // 新增网格
    gridhandleAdd() {
      this.gridReset();
      this.gridOpen = true;
    },

    // 编辑网格
    gridhandleEdit() {
      this.gridReset();
      if (this.guserArr.length > 0) {
        const {
          gridAreaId,
          gridAreaName,
          mainWasteSource,
          duteDept,
          duteLeader,
          phone,
        } = this.guserArr[this.gridActiveindex];
        this.gridform = {
          gridAreaId,
          gridAreaName,
          mainWasteSource,
          duteDept,
          duteLeader,
          phone,
        };
      }

      this.gridOpen = true;
    },

    // 删除网格
    gridhandleDelete() {
      let gridAreaId =this.guserArr.length&&this.guserArr[this.gridActiveindex].gridAreaId;
      let gridAreaName = this.guserArr.length&&this.guserArr[this.gridActiveindex].gridAreaName;
      let gridUserList = this.guserArr.length&&this.guserArr[this.gridActiveindex].gridUserList;

      if (gridUserList && gridUserList.length > 0) {
        this.msgError("当前网格片区下存在网格员,不能删除");
        return;
      }

      this.$confirm('是否确认删除网格"' + gridAreaName + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delGridArea(gridAreaId);
        })
        .then(() => {
          this.getGuserAreaList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },

    // 网格列表
    getGuserAreaList() {
      this.loading = true;
      guserAreaList().then((res) => {
        this.guserArr = res.data;
        if (this.guserArr.length > 0) {
          this.gridList = this.guserArr[this.gridActiveindex].gridUserList;
        }
        this.loading = false;
      });
    },

    /**取消 */
    gridCancel() {
      this.gridOpen = false;
    },
    /** 提交按钮 */
    submitGridForm: function () {
      this.$refs["gridform"].validate((valid) => {
        if (valid) {
          if (this.gridform.gridAreaId != undefined) {
            editGuserArea(this.gridform).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.gridOpen = false;
                this.getGuserAreaList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addGuserArea(this.gridform).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.gridOpen = false;
                this.getGuserAreaList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },

    // 表单重置
    gridReset() {
      this.gridform = {
        gridAreaId: undefined,
        gridAreaName: undefined,
        mainWasteSource: undefined,
        duteDept: undefined,
        duteLeader: undefined,
        phone: undefined,
      };
      this.resetForm("gridform");
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.reset();
      this.title = "新增网格员";
      if (this.guserArr.length > 0) {
        this.gridAreaName = this.guserArr[this.gridActiveindex].gridAreaName;
        this.form.gridAreaId = this.guserArr[this.gridActiveindex].gridAreaId;
      }
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.gridUserId != undefined) {
            editGuser(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getGuserAreaList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addGuser(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getGuserAreaList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        gridUserId: undefined,
        gridAreaId: undefined,
        gridUserName: undefined,
        gridUserPhone: undefined,
        gridUserEmail: undefined,
        gridUserAccount: undefined,
        gridUserPassword: undefined,
        gridUserSex: undefined,
        gridUserStatus: 0,
        gridUserLeaderFlag: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改网格员";
      const {
        gridUserId,
        gridAreaId,
        gridUserName,
        gridUserPhone,
        gridUserEmail,
        gridUserAccount,
        gridUserPassword,
        gridUserSex,
        gridUserStatus,
        gridUserLeaderFlag,
      } = row;
      this.form = {
        gridUserId,
        gridAreaId,
        gridUserName,
        gridUserPhone,
        gridUserEmail,
        gridUserAccount,
        gridUserPassword,
        gridUserSex,
        gridUserStatus,
        gridUserLeaderFlag,
      };
      if (this.guserArr.length > 0) {
        this.gridAreaName = this.guserArr[this.gridActiveindex].gridAreaName;
      }

      this.open = true;
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除网格员为"' + row.gridUserName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delGrid(row.gridUserId);
        })
        .then(() => {
          this.getGuserAreaList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
  },
};
</script>
<style  lang="scss" scoped>
.app-container {
  margin: 20px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  .head-container {
    ul {
      list-style: none;
    }
    .grid {
      li {
        margin-bottom: 10px;
        cursor: pointer;
        width: 120px;
        height: 35px;
        line-height: 35px;
        text-align: left;
        border-radius: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding-left: 10px;
        &:hover {
          background-color: #0064c8;
          color: #fff;
        }
        &.grid-active {
          background-color: #0064c8;
          color: #fff;
        }
      }
    }
  }
}
</style>